using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.NetWork;
using Common;
using GRPCDemo.Protocol;

using XAliphant.Net.Client.Network;
using GrpcClient.Models;
using GrpcClient.Managers;

namespace GrpcClient.Services
{
    public class LicenseService : Singleton<LicenseService>
    {
        public IDictionary<string, ResponseCache> MessageCache = new Dictionary<string, ResponseCache>();

        public void Start()
        {
            MessageDistributer.Instance.Subscribe<LicenseResponse>(OnLicenseResponse);
        }

        public void Stop()
        {
            MessageDistributer.Instance.Unsubscribe<LicenseResponse>(OnLicenseResponse);
        }

        public string LicenseSync(string key, int role, string date)
        {
            NetMessage message = new NetMessage();
            message.Request = new NetMessageRequest();
            message.Request.LicenseRequest = new LicenseRequest();
            message.Request.LicenseRequest.Key = key;
            message.Request.LicenseRequest.Role = role;
            message.Request.LicenseRequest.Date = date;

            NetClient.Instance.SendMessage(message);

            string messageId = "license";
            MessageCache[messageId] = new ResponseCache();
            return messageId;
        }

        private void OnLicenseResponse(object sender, LicenseResponse response)
        {
            string messageId = "license";
            MessageCache[messageId].HasResponse = true;

            if (response.Result == Result.Success)
            {
                LicenseManager.Instance.EncryptLicenseKey(response.Key);
            }
            else
            {
                MessageCache[messageId].ErrMsg = response.Errormsg;
            }
        }
    }
}
